//实现异步缓冲区
#ifndef __M_BUFFER_H__
#define __M_BUFFER_H__
#include<iostream>
#include<cassert>
#include<vector>
#include"util.hpp"
namespace zllog
{
    #define DEFAULT_BUFFER_SIZE (1024 * 1024 * 10)
    #define THRESHOLD_BUFFER_SIZE (1024 * 1024 * 80)
    #define INCREMENT_BUFFER_SIZE (1024 * 1024 *10)
    class Buffer
    {
    public:
        Buffer()
            :_buffer(DEFAULT_BUFFER_SIZE)
            ,writer_idx(0)
            ,reader_idx(0)
        {}
        //向缓冲区写入数据
        void push(const char* data,size_t len)
        {
            //缓冲区空间不够的情况:a.扩容,b.进入阻塞
            //a.固定大小,直接返回,进入阻塞
            // if(len > writeAbleSize())
            // {
            //     return;
            // }
            //b.扩容,动态空间,用于极限性能测试
            ensureEnoughSize(len);

            //1.将数据拷贝进入缓冲区
            std::copy(data,data + len,&_buffer[writer_idx]);
            //2.将当前位置向后移动
            moveWriter(len);
        }
        //对读写指针进行向后偏移操作
        void moveReader(size_t len)
        {
            assert(len <= writer_idx - reader_idx);
            reader_idx += len;
        }
        //对读写指针进行向后偏移操作
        void moveWriter(size_t len)
        {
            assert(len <= _buffer.size() - writer_idx);
            writer_idx += len;
        }
        //返回可读数据的起始地 址
        const char* begin()
        {
            return &_buffer[reader_idx];
        }
        //返回可写数据的长度
        size_t writeAbleSize()
        {
            return _buffer.size() - writer_idx;
        }
        //返回可读数据的长度
        size_t readAbleSize()
        {
            return writer_idx - reader_idx;
        }

        //重置读写位置,初始化缓冲区
        void reset()
        {
            writer_idx = 0;
            reader_idx = 0;
        }
        //对Buffer实现交换操作
        void swap(Buffer& buffer)
        {
            _buffer.swap(buffer._buffer);
            std::swap(writer_idx,buffer.writer_idx);
            std::swap(reader_idx,buffer.reader_idx);
        }
        //判断缓冲区是否为空
        bool empty()
        {
            return (writer_idx == reader_idx);
        }

    private:
        //扩容
        void ensureEnoughSize(size_t len)
        {
            if(len <= writeAbleSize())
            {
                return;
            }
            size_t new_size = 0;
            if(_buffer.size() < THRESHOLD_BUFFER_SIZE)  //小于阈值,指数增长
            {
                new_size = _buffer.size() * 2 + len;
            }
            else      //大于等于阈值,线性增长
            {
                new_size += INCREMENT_BUFFER_SIZE + len;
            }
            _buffer.resize(new_size);
        }
    private:
        std::vector<char> _buffer;
        size_t writer_idx;    //当前可写指针
        size_t reader_idx;   //当前可读指针--本质是下标

    };
};

#endif

